package cz.pproproj.aaservice.guimodule.config;


import org.apache.catalina.connector.Connector;
import org.apache.commons.io.FileUtils;
import org.apache.coyote.http11.Http11NioProtocol;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

@Component
public class ServerConfig {

    @Bean
    public EmbeddedServletContainerFactory servletContainer() {
        TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
        tomcat.addAdditionalTomcatConnectors(createSslConnector());
        return tomcat;
    }

    private Connector createSslConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();

        InputStream keystore = getClass().getResourceAsStream("/private/.keystore");
        File tmpDir = new File(System.getProperty("user.dir"));
        File tmpKeystore = new File(tmpDir, "aas.keystore");
        try {
            if (!tmpKeystore.exists()) {
                FileUtils.copyInputStreamToFile(keystore, tmpKeystore);
            }
        } catch (IOException e) {
            throw new RuntimeException("Unable to copy keystore file into tempDir: " + tmpKeystore.getPath(), e);
        }
        try {
            connector.setScheme("https");
            connector.setSecure(true);
            connector.setPort(8443);
            protocol.setSSLEnabled(true);
            protocol.setKeystoreFile(tmpKeystore.getPath());
            protocol.setKeystorePass("authauto");
            protocol.setTruststoreFile(tmpKeystore.getPath());
            protocol.setTruststorePass("authauto");
            protocol.setKeyAlias("tomcat");
            protocol.setKeystoreType("JKS");
            protocol.setSslProtocol("TLS");
            protocol.setClientAuth("false");
            return connector;
        } catch (RuntimeException ex) {
           throw new RuntimeException("HTTPS",ex);
        }
    }
}
